package com.sumainfor.wx.tenant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sumainfor.common.entity.WxUserEntity;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.wx.tenant.entity.*;
import com.sumainfor.wx.tenant.feign.MarketFeignClient;
import com.sumainfor.wx.tenant.service.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Jack Chen
 * @Create 2019-02-13 16:25
 * 房源操作
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class HousingFindServiceImpl implements HousingFindService {

    @Autowired
    private MarketFeignClient marketFeignClient;

    @Autowired
    private TctenTenantLikeService likeService;

    @Autowired
    private TctenTenantWorkService workService;

    @Autowired
    private TctenTenantIdentitService cardService;

    @Autowired
    private TctenTenantIndirectionService indirectionService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static final String WORKSPACE = HousingFindServiceImpl.class.getSimpleName() + "-HotSearchKey";

    @Autowired
    private TctenTenantSeahistoryService historyService;

    /**
     * 房源查找
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult findHousing(Map<String, Object> params) {
        String key = MapUtils.getString(params, "searchKeyWord");
        if (StringUtils.isNotBlank(key)) {
            addSearchHotCount(key);
            //添加搜索历史
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("Seacontent", key);
            queryWrapper.eq("TenId", ContextUtils.getWxInfo().getTenId());
            int count = historyService.count(queryWrapper);
            if (count == 0) {
                TctenTenantSeahistory entity = new TctenTenantSeahistory();
                entity.setSeacode(UUIDUtils.generateShortUuid());
                entity.setTenId(ContextUtils.getWxInfo().getTenId());
                entity.setDelfg(0);
                entity.setSeacontent(key);
                boolean row = historyService.save(entity);
                if (row == false) {
                    log.error("插入租客搜索历史失败");
                }
            }
        }
        return marketFeignClient.findHousingDataList(params);
    }

    /**
     * 添加热门搜索到Redis 缓存中去
     *
     * @param keyWord
     */
    public void addSearchHotCount(String keyWord) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        //判断是否存在这个KEY
        if (opsForHash.hasKey(WORKSPACE, keyWord)) {
            //如果存在的  进行加1操作
            opsForHash.increment(WORKSPACE, keyWord, 1);
        } else {
            //如果不存在  存入这个KEY
            opsForHash.put(WORKSPACE, keyWord, String.valueOf(1));
        }
    }


    public Map<Object, Object> getAll() {
        if (stringRedisTemplate.hasKey(WORKSPACE)) {
            HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
            Map<Object, Object> map = opsForHash.entries(WORKSPACE);
            if (map.isEmpty()) {
                return null;
            }
            return map;
        }
        return null;
    }


    /**
     * 获取热门的搜索
     *
     * @param size 要获取的长度
     * @return
     */
    @Override
    public List<String> getHotList(int size) {
        List<String> res = new ArrayList<>();
        Map<Object, Object> map = getAll();
        if (map == null || map.isEmpty()) {
            return res;
        }
        List<Map.Entry<Object, Object>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            long v1 = Long.valueOf((String) o1.getValue());
            long v2 = Long.valueOf((String) o2.getValue());
            return (int) (v2 - v1);
        });
        int length = list.size() > size ? size : list.size();
        for (int i = 0; i < length; i++) {
            res.add((String) list.get(i).getKey());
        }
        return res;
    }

    /**
     * 获取历史搜索记录
     *
     * @return
     */
    @Override
    public List<String> getHistorySearch() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("TenId", ContextUtils.getWxInfo().getTenId());
        List<TctenTenantSeahistory> list = historyService.list(queryWrapper);
        return list.stream().map(item -> item.getSeacontent()).collect(Collectors.toList());
    }

    /**
     * 清空历史搜索记录
     *
     * @return
     */
    @Override
    public boolean clearHistorySearchData() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("TenId", ContextUtils.getWxInfo().getTenId());
        boolean remove = historyService.remove(queryWrapper);
        return remove;
    }

    /**
     * 根据编号查询房源的详细信息
     *
     * @param infoId
     * @return
     */
    @Override
    public JsonResult getHousingInfoById(String infoId) {
        JsonResult result = marketFeignClient.getHousingInfoByInfoId(infoId);
        if (result.isSuccess() == false) {
            return result;
        }
        Map<String, Object> map = (Map<String, Object>) result.getResult();

        //判断我是否添加了喜爱
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("HouInfoId", infoId);
        int count = likeService.count(wrapper);
        if (count != 0) {
            map.put("isLike", true);
        } else {
            map.put("isLike", false);
        }

        return result;
    }


    /**
     * 添加到我的喜爱
     *
     * @param infoId
     * @return
     */
    @Override
    public JsonResult actionLikeHousing(String infoId) {
        //先判断是否存在这个房源信息
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("HouInfoId", infoId);
        wrapper.eq("TenId", ContextUtils.getWxInfo().getTenId());
        int count = likeService.count(wrapper);
        if (count != 0) {
            //存在将其移除掉
            boolean state = likeService.remove(wrapper);
            return state ? JsonResult.success(false) : JsonResult.actionFailure();
        }

        TctenTenantLike like = new TctenTenantLike();
        like.setTenId(ContextUtils.getWxInfo().getTenId());
        like.setLicode(UUIDUtils.generatePrefixUuid("Like"));
        JsonResult result = this.getHousingInfoById(infoId);
        if (!result.isSuccess()) {
            return result;
        }
        Map<String, Object> map = (Map<String, Object>) result.getResult();
        like.setHouId(MapUtils.getString(map, "HouId"));
        like.setHouInfoId(MapUtils.getString(map, "HouInfoId"));
        like.setHouname(MapUtils.getString(map, "HouInfoName"));
        like.setHouimg(MapUtils.getString(map, "ShowImg"));
        like.setArea(Double.valueOf(MapUtils.getString(map, "Area").replaceAll("m²", "")));
        like.setProLoculus(MapUtils.getInteger(map, "ProLoculus"));
        like.setProHall(MapUtils.getInteger(map, "ProHall"));
        like.setProGuard(MapUtils.getInteger(map, "ProGuard"));
        like.setAspect(MapUtils.getString(map, "Towards"));
        like.setRentmoney(ObjectUtil.convertBigDecimal(MapUtils.getString(map, "UnifiedPricing")));
        like.setState(0);
        like.setFloor(MapUtils.getInteger(map, "Floor"));
        like.setFloors(MapUtils.getInteger(map, "Floors"));
        like.setDelfg(0);
        like.setInstm(LocalDateTime.now());
        boolean state = likeService.save(like);
        return state ? JsonResult.success(true) : JsonResult.actionFailure();
    }


    /**
     * 发起预约房源
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult makeHousing(Map<String, Object> params) {
        String infoId = MapUtils.getString(params, "infoId");
        if(!FieldCheckUtil.isMapFieldNotNull(params,new String[]{"date"})){
            params.put("date", ConvertDateTime.getCurrentTimes("yyyy-MM-dd HH:mm"));
        }
        String date = MapUtils.getString(params, "date");
        String remark = MapUtils.getString(params, "remark");
        String shelfId = MapUtils.getString(params, "shelfId");

        //查询构建数据
        WxUserEntity userEntity = ContextUtils.getWxInfo();

        //查询租客详情-工作信息
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("TenId", userEntity.getTenId());
        TctenTenantWork work = workService.getOne(wrapper);

        //行业信息
        String inmname = "";
        if (work != null && work.getIncode() != null) {
            QueryWrapper hang = new QueryWrapper();
            hang.eq("Incode", work.getIncode());
            TctenTenantIndirection indirection = indirectionService.getOne(hang);
            inmname = indirection.getInmname();
        }

        //查询租客的身份证信息
        TctenTenantIdentit card = cardService.getOne(wrapper);
        if (card == null) {
            card = new TctenTenantIdentit();
        }

        if (work == null) {
            work = new TctenTenantWork();
        }

        CustomMap data = CustomMap.create("TenId", userEntity.getTenId())
                .put("SetId", shelfId)
                .put("openid", userEntity.getOpenid())
                .put("SeTime", date)
                .put("MakeUserName", params.get("MakeUserName"))
                .put("Remark", remark)
                .put("HouInfoId", infoId)
                .put("State", 0)
                .put("IfState", 0)
                .put("TenName", userEntity.getTenName())
                .put("TenType", 0)
                .put("TenMode", userEntity.getTenPhone())
                //自来客编号
                .put("SoId", "SO-201811090008")
                .put("Company", work.getComname())
                .put("Contact", work.getEmcontact())
                .put("EcPhone", work.getEmcontactphone())
                .put("IdType", card.getCertiftype())
                .put("TenIdno", card.getIDNumber())
                .put("IdPositive", card.getFrontphoto())
                .put("IdContrary", card.getFrontpside())
                //职业名称
                .put("JobName", inmname);

        return marketFeignClient.makeHousing(data);
    }

    /**
     * 房源预约列表详情查看
     *
     * @return
     */
    @Override
    public JsonResult getMakeHousingList() {
        String tenId = ContextUtils.getWxInfo().getTenId();
        return marketFeignClient.getMakeHousingList(tenId);
    }


    /**
     * 评价一个预约单
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult commentMakeOrder(Map<String, Object> params) {
        ContextUtils.getWxInfo().getTenId();
        return marketFeignClient.commentMakeOrder(params);
    }
}
